import React, { Component } from 'react'
import { Switch, Route, withRouter, Redirect } from 'react-router'
import Login from '../components/Login'
import Index from '../components/Index'
import Cart from '../components/Cart'
import My from '../components/My'

export default class Router extends Component {
  constructor() {
    super();
    this.state = {
      routes: [
        {
          path: '/index',
          component: Index,
          exact: false,
          meta: '首页',
          needLogin: false
        },
        {
          path: '/login',
          component: Login,
          exact: false,
          meta: '登录',
          needLogin: false
        },
        {
          path: '/cart',
          component: Cart,
          exact: false,
          meta: '购物车',
          needLogin: true
        },
        {
          path: '/my',
          component: My,
          exact: false,
          meta: '我的',
          needLogin: true
        },
        {
          exact: true,
          path: '/',
          to: '/index'
        },
      ]
    }
  }
  render() {
    return (
      <div>
        <Switch>
          {
            this.state.routes.map((item, index) => {
              // 正常的路由，有component
              if (item.component) {
                return (
                  <Route key={index} path={item.path} exact={item.exact}
                    // 每次渲染路由都会执行render，可以代替component
                    render={() => {
                      // 修改页面标题
                      if (item.meta) {
                        document.title = item.meta
                      }
                      // 判断是否需要登录
                      if (item.needLogin) {
                        let isLogin = true; // isLogin可以从localStorege中获取
                        if (!isLogin) {
                          return (
                            <Redirect to="/login"></Redirect>
                          )
                        }
                      }
                      let Component = withRouter(item.component);
                      return <Component></Component>
                    }}
                  ></Route>
                )
              }
              // 没有component的路由，是一个重定向
              return (<Route key={index} exact={item.exact} path={item.path}>
                <Redirect to={item.to}></Redirect>
              </Route>)
            })
          }
        </Switch>
      </div>
    )
  }
}
